﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Design;

namespace ProgNetComponents.Design.Editors
{
    /// <summary>
    /// Gets editor for selecting type
    /// </summary>
    public abstract class BaseClassTypeEditor : BaseListEditor
    {
        /// <summary>
        /// Gets Base Type for types that will be displatyed in dropdown
        /// </summary>
        protected abstract Type ClassType
        {
            get;
        }
        /// <summary>
        /// Fills collection with 
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override bool FillCollection(Collections.NamedObjectCollection collection, System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IDesignerHost host = provider.GetService<IDesignerHost>();

            if (host != null)
            {
                try
                {
                    Type[] types = provider.GetTypes(ClassType);
                    if (types != null && types.Length > 0)
                    {
                        foreach (Type t2 in types)
                            AddType(t2);
                    }
                    return true;
                }
                catch { }
            }
            return false;
        }
        private void AddType(Type t)
        {
            if (collection.Contains(t.Name))
            {
                Type t2 = collection[t.Name].Value as Type;
                collection.Remove(t.Name);
                collection.Add(t2.FullName, t2);

                collection.Add(t.FullName, t);
            }
            else
            {
                collection.Add(t.Name, t);
            }
        }
    }
    /// <summary>
    /// Editor with all types that inherit from T class
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseClassTypeEditor<T> : BaseClassTypeEditor
    {
        /// <summary>
        /// Gets Base Type for types that will be displatyed in dropdown
        /// </summary>
        protected override Type ClassType
        {
            get { return typeof(T); }
        }
    }
}
